import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { InventoryTransferService } from './inventory-transfer.service';
import { InventoryTransferDto } from './models';
import { TransferDataService } from '../shared/services/transfer-data.service';
import { OutOrderService } from '../OutOrder/out-order.service';

@Component({
  selector: 'app-inventory-transfer-detail',
  templateUrl: './inventory-transfer-detail.component.html',
  styleUrls: ['./inventory-transfer-detail.component.scss'],
  standalone: true,
  imports: [CommonModule]
})
export class InventoryTransferDetailComponent implements OnInit {
  transfer: InventoryTransferDto | null = null;
  isLoading = true;
  currentTab: string = 'detail'; // 默认显示调拨明细

  // 新增：调出弹窗相关
  isOutOrderModalOpen = false;
  outOrderData: any = null;

  constructor(
    private route: ActivatedRoute,
    private inventoryTransferService: InventoryTransferService,
    private router: Router,
    private transferDataService: TransferDataService,
    private outOrderService: OutOrderService // 新增注入
  ) {}

  ngOnInit(): void {
    const id = this.route.snapshot.paramMap.get('id');
    console.log('详情页id:', id);
    if (id) {
      this.inventoryTransferService.get(id).subscribe({
        next: (data) => {
          console.log('详情数据:', data);
          this.transfer = data;
          this.isLoading = false;
        },
        error: (err) => {
          console.error('详情接口报错', err);
          this.isLoading = false;
        }
      });
    }
  }

  getTotalQuantity(): number {
    const list = this.transfer?.merchandiseList || this.transfer?.details || [];
    return list.reduce((sum, d) => sum + Number(d.merchandiseNumber || d.MerchandiseNumber || 0), 0);
  }

  getTotalAmount(): number {
    const list = this.transfer?.merchandiseList || this.transfer?.details || [];
    return list.reduce((sum, d) => sum + Number(d.merchandisePrice || d.MerchandisePrice || 0), 0);
  }

  goToOutOrder() {
    const id = this.route.snapshot.paramMap.get('id');
    if (!id) return;
    this.outOrderService.createFromInventoryTransfer(id).subscribe({
      next: (outOrder) => {
        this.outOrderData = outOrder;
        // 初始化本次出库数量为0
        if (this.outOrderData.details) {
          this.outOrderData.details.forEach(d => d.currentOutNumber = 0);
        }
        this.isOutOrderModalOpen = true;
      },
      error: (err) => {
        alert('生成出库单失败');
      }
    });
  }

  closeOutOrderModal() {
    this.isOutOrderModalOpen = false;
    this.outOrderData = null;
  }

  saveOutOrder() {
    // 校验：不允许本次出库数量大于未出库数量
    let valid = true;
    if (this.outOrderData.details) {
      for (let d of this.outOrderData.details) {
        if (d.currentOutNumber > (d.merchandiseNumber || d.MerchandiseNumber)) {
          valid = false;
          break;
        }
      }
    }
    if (!valid) {
      alert('不允许大于未出库数量!');
      return;
    }
    // TODO: 提交保存逻辑
    this.isOutOrderModalOpen = false;
  }

  removeDetail(index: number) {
    if (this.outOrderData && this.outOrderData.details) {
      this.outOrderData.details.splice(index, 1);
    }
  }

  getTotalNumber() {
    if (!this.outOrderData?.details) return 0;
    return this.outOrderData.details.reduce((sum, d) => sum + (d.merchandiseNumber || d.MerchandiseNumber || 0), 0);
  }

  getTotalCurrentOutNumber() {
    if (!this.outOrderData?.details) return 0;
    return this.outOrderData.details.reduce((sum, d) => sum + (Number(d.outOrderNumber) || 0), 0);
  }

  getTotalOutOrderAmount() {
    if (!this.outOrderData?.details) return 0;
    return this.outOrderData.details.reduce((sum, d) => sum + ((Number(d.outOrderNumber) || 0) * (Number(d.merchandiseINPrice) || 0)), 0);
  }
} 